package net.xiduth.utils.player;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 
 * @author Kova+
 *
 */
public class LogsZipper {
	
	public static void zipLogs(String name) {
        File f1 = new File("./data/playersaves/logs/"+ name);
        File f2 = new File("./data/playersaves/zippedLogs/"+name+" - All Logs.zip");
        if (!f1.exists()) {
        	System.out.println("Logs for " + name + " do not exist.");
        	return;
        }
        if (!f2.exists()) {
            try {
                System.out.println("Gathering and Zipping logs for " + name);
                zipDirectory(f1, f2);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("Those log's are already zipped!");
        }
    }
	
	 public static final void zipDirectory(File f, File zf) throws IOException {
	        ZipOutputStream z = new ZipOutputStream(new FileOutputStream(zf));
	        zip(f, f, z);
	        z.close();
	    }
	 
	    private static final void zip(File directory, File base, ZipOutputStream zos) throws IOException {
	        File[] files = directory.listFiles();
	        byte[] buffer = new byte[8192];
	        int read = 0;
	        for (int i = 0, n = files.length; i < n; i++) {
	            if (files[i].isDirectory()) {
	                zip(files[i], base, zos);
	            } else {
	                FileInputStream in = new FileInputStream(files[i]);
	                ZipEntry entry = new ZipEntry(files[i].getPath().substring(base.getPath().length() + 1));
	                zos.putNextEntry(entry);
	                while (-1 != (read = in.read(buffer))) {
	                    zos.write(buffer, 0, read);
	                }
	                in.close();
	                 }
	        }
	    }
}